package com.file.system.plugin.shiro.filter;


import com.file.system.entity.res.BaseCode;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.system.WebUser;
import com.file.system.plugin.shiro.ShiroTools;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import static cn.hutool.core.util.ObjectUtil.equal;
import static cn.hutool.crypto.digest.DigestUtil.md5Hex;
import static cn.hutool.json.JSONUtil.toJsonStr;

/**
 * 通过字符串验证权限
 *
 * @date
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {
    private ShiroTools shiroTools = new ShiroTools();

   public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        // 获取响应对象
        HttpServletResponse httpResponse = shiroTools.getHttpResponse(response);
        // 获取用户信息
        WebUser user = shiroTools.getShiroUser();

        // 判断用户是否为空
        if (user == null) {
            // 用户未登录
            String json = toJsonStr(CommonResult.fail(BaseCode.Common.USER_NOT_LOGIN));
            // 返回未登录状态
            httpResponse.getWriter().write(json);
            return false;
        }

        // 判断密码是否简单
        if (equal(user.getPassword(), md5Hex(md5Hex(user.getUsername())))) {
            // 密码简单
            String json = toJsonStr(CommonResult.fail(BaseCode.Common.USER_WEAK_PASSWORD));
            // 返回简单密码状态
            httpResponse.getWriter().write(json);
            return false;
        }

        return true;
    }


}